#include "interruptManager.h"
#include "cpuSimulator.h"
#include "fileSystemHandler.h"
#include "inputOutputHandler.h"
#include "mathHandler.h"
#include "stringHandler.h"
#include "systemInfoHandler.h"
#include "systemCallHandler.h"
#include <QDebug>

/**
 * @brief InterruptManager构造函数
 * @param parent 父对象
 */
InterruptManager::InterruptManager(QObject *parent)
    : QObject(parent)
    , fileSystemHandler(nullptr)
    , inputOutputHandler(nullptr)
    , mathHandler(nullptr)
    , stringHandler(nullptr)
    , systemInfoHandler(nullptr)
    , debugMode(false)
{
    initializeHandlers();
}

/**
 * @brief InterruptManager析构函数
 */
InterruptManager::~InterruptManager()
{
    // 智能指针会自动清理资源
}

/**
 * @brief 初始化中断处理器
 */
void InterruptManager::initializeHandlers()
{
    try {
        // 创建各个处理器实例
        fileSystemHandler = SystemCallHandlerFactory::createFileSystemHandler(this);
        inputOutputHandler = SystemCallHandlerFactory::createInputOutputHandler(this);
        mathHandler = SystemCallHandlerFactory::createMathHandler(this);
        stringHandler = SystemCallHandlerFactory::createStringHandler(this);
        systemInfoHandler = SystemCallHandlerFactory::createSystemInfoHandler(this);

        // 连接信号槽
        if (fileSystemHandler) {
            connect(fileSystemHandler.get(), &SystemCallHandler::interruptHandled,
                    this, &InterruptManager::onInterruptHandled);
            connect(fileSystemHandler.get(), &SystemCallHandler::outputMessage,
                    this, &InterruptManager::outputMessage);
            connect(fileSystemHandler.get(), &SystemCallHandler::errorMessage,
                    this, [this](const QString& message) {
                        emit errorOccurred(-1, QString("文件系统错误: %1").arg(message));
                    });
        }

        if (inputOutputHandler) {
            connect(inputOutputHandler.get(), &SystemCallHandler::interruptHandled,
                    this, &InterruptManager::onInterruptHandled);
            connect(inputOutputHandler.get(), &SystemCallHandler::outputMessage,
                    this, [this](const QString& message) {
                        qDebug() << "InterruptManager收到inputOutputHandler的outputMessage信号:" << message;
                        qDebug() << "InterruptManager即将转发outputMessage信号:" << message;
                        emit outputMessage(message);
                        qDebug() << "InterruptManager已发射outputMessage信号:" << message;
                    });
            connect(inputOutputHandler.get(), &SystemCallHandler::errorMessage,
                    this, [this](const QString& message) {
                        emit errorOccurred(-1, QString("输入输出错误: %1").arg(message));
                    });
        }

        if (mathHandler) {
            connect(mathHandler.get(), &SystemCallHandler::interruptHandled,
                    this, &InterruptManager::onInterruptHandled);
            connect(mathHandler.get(), &SystemCallHandler::outputMessage,
                    this, &InterruptManager::outputMessage);
            connect(mathHandler.get(), &SystemCallHandler::errorMessage,
                    this, [this](const QString& message) {
                        emit errorOccurred(-1, QString("数学运算错误: %1").arg(message));
                    });
        }

        if (stringHandler) {
            connect(stringHandler.get(), &SystemCallHandler::interruptHandled,
                    this, &InterruptManager::onInterruptHandled);
            connect(stringHandler.get(), &SystemCallHandler::outputMessage,
                    this, &InterruptManager::outputMessage);
            connect(stringHandler.get(), &SystemCallHandler::errorMessage,
                    this, [this](const QString& message) {
                        emit errorOccurred(-1, QString("字符串处理错误: %1").arg(message));
                    });
        }

        if (systemInfoHandler) {
            connect(systemInfoHandler.get(), &SystemCallHandler::interruptHandled,
                    this, &InterruptManager::onInterruptHandled);
            connect(systemInfoHandler.get(), &SystemCallHandler::outputMessage,
                    this, &InterruptManager::outputMessage);
            connect(systemInfoHandler.get(), &SystemCallHandler::errorMessage,
                    this, [this](const QString& message) {
                        emit errorOccurred(-1, QString("系统信息错误: %1").arg(message));
                    });
        }

        // 清空统计数据
        interruptStatistics.clear();

        if (debugMode) {
            qDebug() << "InterruptManager: 所有处理器初始化完成";
        }

    } catch (const std::exception& e) {
        qWarning() << "InterruptManager初始化失败:" << e.what();
        emit errorOccurred(-1, QString("中断管理器初始化失败: %1").arg(e.what()));
    }
}

/**
 * @brief 处理中断调用
 * @param interruptNumber 中断号
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult InterruptManager::handleInterrupt(int interruptNumber, CpuSimulator* cpu)
{
    if (!cpu) {
        QString errorMsg = "CPU模拟器指针为空";
        if (debugMode) {
            qDebug() << "InterruptManager错误:" << errorMsg;
        }
        return SystemCallResult(false, -1, errorMsg);
    }

    // 更新统计信息
    interruptStatistics[interruptNumber]++;

    if (debugMode) {
        qDebug() << QString("InterruptManager: 处理中断 0x%1")
                    .arg(interruptNumber, 2, 16, QChar('0'));
    }

    try {
        // 根据中断号范围选择相应的处理器
        SystemCallHandler* handler = getHandlerForInterrupt(interruptNumber);
        
        if (!handler) {
            QString errorMsg = QString("不支持的中断号: 0x%1")
                              .arg(interruptNumber, 2, 16, QChar('0'));
            if (debugMode) {
                qDebug() << "InterruptManager:" << errorMsg;
            }
            return SystemCallResult(false, -2, errorMsg);
        }

        // 执行中断处理
        SystemCallResult result = handler->handleInterrupt(interruptNumber, cpu);

        if (debugMode) {
            QString status = result.success ? "成功" : "失败";
            qDebug() << QString("中断 0x%1 处理%2")
                        .arg(interruptNumber, 2, 16, QChar('0'))
                        .arg(status);
            if (!result.success) {
                qDebug() << "错误信息:" << result.errorMessage;
            }
        }

        // 暂时注释掉信号发射，避免死锁
        // 发射信号
        // if (result.success) {
        //     emit interruptHandled(interruptNumber, result);
        // } else {
        //     emit errorOccurred(QString("中断 0x%1 处理失败: %2")
        //                       .arg(interruptNumber, 2, 16, QChar('0'))
        //                       .arg(result.errorMessage));
        // }

        return result;

    } catch (const std::exception& e) {
        QString errorMsg = QString("中断处理异常: %1").arg(e.what());
        if (debugMode) {
            qDebug() << "InterruptManager异常:" << errorMsg;
        }
        // 暂时注释掉信号发射，避免死锁
        // emit errorOccurred(errorMsg);
        return SystemCallResult(false, -3, errorMsg);
    }
}

/**
 * @brief 根据中断号获取对应的处理器
 * @param interruptNumber 中断号
 * @return SystemCallHandler* 处理器指针，nullptr表示不支持
 */
SystemCallHandler* InterruptManager::getHandlerForInterrupt(int interruptNumber) const
{
    // 文件操作中断 (0x10-0x1F)
    if (interruptNumber >= 0x10 && interruptNumber <= 0x1F) {
        return fileSystemHandler.get();
    }
    // 输入输出中断 (0x20-0x2F)
    else if (interruptNumber >= 0x20 && interruptNumber <= 0x2F) {
        return inputOutputHandler.get();
    }
    // 字符串操作中断 (0x30-0x3F)
    else if (interruptNumber >= 0x30 && interruptNumber <= 0x3F) {
        return stringHandler.get();
    }
    // 数学运算中断 (0x40-0x4F)
    else if (interruptNumber >= 0x40 && interruptNumber <= 0x4F) {
        return mathHandler.get();
    }
    // 系统信息和内存管理中断 (0x50-0x6F)
    else if (interruptNumber >= 0x50 && interruptNumber <= 0x6F) {
        return systemInfoHandler.get();
    }
    
    return nullptr;
}

/**
 * @brief 重置所有处理器状态
 */
void InterruptManager::reset()
{
    if (debugMode) {
        qDebug() << "InterruptManager: 重置所有处理器";
    }

    try {
        // 重置各个处理器
        if (fileSystemHandler) {
            fileSystemHandler->reset();
        }
        if (inputOutputHandler) {
            inputOutputHandler->reset();
        }
        if (mathHandler) {
            mathHandler->reset();
        }
        if (stringHandler) {
            stringHandler->reset();
        }
        if (systemInfoHandler) {
            systemInfoHandler->reset();
        }

        // 清空统计数据
        interruptStatistics.clear();

        if (debugMode) {
            qDebug() << "InterruptManager: 重置完成";
        }

        emit resetCompleted();

    } catch (const std::exception& e) {
        QString errorMsg = QString("重置处理器失败: %1").arg(e.what());
        if (debugMode) {
            qDebug() << "InterruptManager异常:" << errorMsg;
        }
        emit errorOccurred(-1, errorMsg);
    }
}

/**
 * @brief 获取中断调用统计信息
 * @return QMap<int, int> 中断号到调用次数的映射
 */
QMap<int, int> InterruptManager::getInterruptStatistics() const
{
    return interruptStatistics;
}

/**
 * @brief 获取支持的中断号列表
 * @return QList<int> 支持的中断号列表
 */
QList<int> InterruptManager::getSupportedInterrupts() const
{
    QList<int> supportedInterrupts;
    
    // 文件操作中断 (0x10-0x1F)
    for (int i = 0x10; i <= 0x1F; ++i) {
        supportedInterrupts.append(i);
    }
    
    // 输入输出中断 (0x20-0x2F)
    for (int i = 0x20; i <= 0x2F; ++i) {
        supportedInterrupts.append(i);
    }
    
    // 字符串操作中断 (0x30-0x3F)
    for (int i = 0x30; i <= 0x3F; ++i) {
        supportedInterrupts.append(i);
    }
    
    // 数学运算中断 (0x40-0x4F)
    for (int i = 0x40; i <= 0x4F; ++i) {
        supportedInterrupts.append(i);
    }
    
    // 系统信息和内存管理中断 (0x50-0x6F)
    for (int i = 0x50; i <= 0x6F; ++i) {
        supportedInterrupts.append(i);
    }
    
    return supportedInterrupts;
}

/**
 * @brief 设置调试模式
 * @param enabled 是否启用调试模式
 */
void InterruptManager::setDebugMode(bool enabled)
{
    debugMode = enabled;
    if (debugMode) {
        qDebug() << "InterruptManager: 调试模式已启用";
    }
}

/**
 * @brief 检查中断号是否受支持
 * @param interruptNumber 中断号
 * @return bool 是否支持
 */
bool InterruptManager::isInterruptSupported(int interruptNumber) const
{
    return getHandlerForInterrupt(interruptNumber) != nullptr;
}

/**
 * @brief 获取中断描述信息
 * @param interruptNumber 中断号
 * @return QString 中断描述
 */
QString InterruptManager::getInterruptDescription(int interruptNumber) const
{
    SystemCallHandler* handler = getHandlerForInterrupt(interruptNumber);
    
    if (!handler) {
        return QString("不支持的中断号: 0x%1").arg(interruptNumber, 2, 16, QChar('0'));
    }
    
    // 根据中断号范围返回描述
    if (interruptNumber >= 0x10 && interruptNumber <= 0x1F) {
        return QString("文件系统操作 - %1").arg(handler->getDescription());
    } else if (interruptNumber >= 0x20 && interruptNumber <= 0x2F) {
        return QString("输入输出操作 - %1").arg(handler->getDescription());
    } else if (interruptNumber >= 0x30 && interruptNumber <= 0x3F) {
        return QString("字符串操作 - %1").arg(handler->getDescription());
    } else if (interruptNumber >= 0x40 && interruptNumber <= 0x4F) {
        return QString("数学运算 - %1").arg(handler->getDescription());
    } else if (interruptNumber >= 0x50 && interruptNumber <= 0x6F) {
        return QString("系统信息/内存管理 - %1").arg(handler->getDescription());
    }
    
    return "未知中断类型";
}

/**
 * @brief 清空中断统计信息
 */
void InterruptManager::clearStatistics()
{
    interruptStatistics.clear();
    if (debugMode) {
        qDebug() << "InterruptManager: 统计信息已清空";
    }
}

/**
 * @brief 获取最常用的中断号
 * @param count 返回的数量
 * @return QList<QPair<int, int>> 中断号和调用次数的配对列表，按调用次数降序排列
 */
QList<QPair<int, int>> InterruptManager::getMostUsedInterrupts(int count) const
{
    QList<QPair<int, int>> sortedInterrupts;
    
    // 转换为配对列表
    for (auto it = interruptStatistics.constBegin(); it != interruptStatistics.constEnd(); ++it) {
        sortedInterrupts.append(qMakePair(it.key(), it.value()));
    }
    
    // 按调用次数降序排序
    std::sort(sortedInterrupts.begin(), sortedInterrupts.end(),
              [](const QPair<int, int>& a, const QPair<int, int>& b) {
                  return a.second > b.second;
              });
    
    // 返回前count个
    if (count > 0 && count < sortedInterrupts.size()) {
        return sortedInterrupts.mid(0, count);
    }
    
    return sortedInterrupts;
}

/**
 * @brief 处理中断完成槽函数
 * @param interruptNumber 中断号
 * @param result 处理结果
 */
void InterruptManager::onInterruptHandled(int interruptNumber, const SystemCallResult& result)
{
    if (debugMode) {
        qDebug() << QString("中断 0x%1 处理完成: %2")
                    .arg(interruptNumber, 2, 16, QChar('0'))
                    .arg(result.success ? "成功" : "失败");
    }
    
    // 转发信号
    emit interruptHandled(interruptNumber, result);
} 